let tokenTypes = require('../common/token-types');
let expressionParser = require('./expression-parser');
let operatorParser = require('./operator-parser');

let syntaxParser = {
  result: [],
  parse(tokens) {
    let tokenChunks = this.splitTokens(tokens);
    tokenChunks.forEach(chunk => {
      let result = {};
      let isExp = chunk.some(token => {
        return [tokenTypes.ASSIGN, tokenTypes.POINT].includes(token.type);
      });
      if (isExp) {
        result = expressionParser.parse(chunk);
      } else {
        if (chunk[0].type == tokenTypes.WORD) {
          result = operatorParser.parse(chunk);
        } else {
          result = expressionParser.parse(chunk);
        }
      }
      this.result.push(result);
    });
    return this.result;
  },
  splitTokens(tokens) {
    let result = [];
    let chunk = [];
    tokens.forEach(token => {
      if (token.type != tokenTypes.SEMI) {
        chunk.push(token);
      } else {
        result.push(chunk);
        chunk = [];
      }
    });
    result.push(chunk);
    return result;
  }
};

module.exports = syntaxParser;
